package com.chuangjiangx.member.stored.ddd.domain;

import com.chuangjiangx.member.stored.ddd.domain.stardard.MbrPaymentContext;
import com.chuangjiangx.member.stored.ddd.domain.stardard.MbrPaymentResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.function.BiConsumer;
import java.util.function.Predicate;

/**
 * @author cj-ch
 * @date 2018/4/6 下午12:56
 */
public abstract class AbstractMbrPayment implements MbrPayment {
    protected final Logger logger = LoggerFactory.getLogger("pay");
    protected MbrPaymentContext paymentContext;


    public AbstractMbrPayment(MbrPaymentContext paymentContext) {
        this.paymentContext = paymentContext;
    }



    /**
     * 支付前
     */
    private Predicate<MbrPaymentContext> beforePayment;
    /**
     * 支付后
     */
    private BiConsumer<MbrPaymentContext, MbrPaymentResult> afterPayment;


    /**
     * 由子类具体实现支付
     *
     * @return
     */
    protected abstract MbrPaymentResult pay();



    @Override
    public MbrPaymentResult payment() {
        if (beforePayment != null && !beforePayment.test(this.paymentContext)) {
            //支付前置条件检查不通过时抛出异常
        }
        //执行支付业务代码
        MbrPaymentResult mbrPaymentResult = pay();
        if (afterPayment != null) {
            //支付后业务逻辑处理
            afterPayment.accept(this.paymentContext,mbrPaymentResult);
        }
        return mbrPaymentResult;
    }



    public AbstractMbrPayment andBeforePayment(Predicate<MbrPaymentContext> predicate) {
        if (this.beforePayment == null) {
            this.beforePayment = predicate;
        } else {
            this.beforePayment = this.beforePayment.and(predicate);

        }
        return this;
    }

    public AbstractMbrPayment andAfterPayment(BiConsumer<MbrPaymentContext, MbrPaymentResult> consumer) {
        if (this.afterPayment == null) {
            this.afterPayment = consumer;
        } else {
            this.afterPayment = this.afterPayment.andThen(consumer);
        }
        return this;
    }


}
